package ext.acae2.cad;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.util.Map;

import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;
import jcifs.smb.SmbFileOutputStream;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.log4j.Logger;

import ext.acae2.util.FileUtil;

import wt.log4j.LogR;

/**
 * @desription 调用UG服务器进行CAD电子签名
 * @author cnie
 * @date 2013-7-18 上午9:57:38
 */
public class UGServerHelper {
	private static final Logger LOGGER = LogR.getLogger(UGServerHelper.class
			.getName());

	/**
	 * 
	 * @description 上传文件到UG服务器上
	 * @author cnie
	 * @date 2013-7-18 上午10:17:48
	 * @version 1.0
	 * @param tempFolder
	 *            当前服务器模型存放的直接文件夹
	 * @param serverfolderPath
	 *            UGserver创建的临时文件夹
	 * @return
	 * @throws MalformedURLException
	 * @throws SmbException
	 */
	public static boolean uploadPrimaryFileToUGServer(File tempFolder,
			String serverfolderPath) throws MalformedURLException, SmbException {
		LOGGER.debug("uploadPrimaryFileToUGServer>>>>>>>>>>>>>start");
		File[] localFiles = tempFolder.listFiles();

		SmbFile ugtemp = new SmbFile(serverfolderPath);
		if (!ugtemp.exists()) {
			ugtemp.mkdirs();
		}
		boolean b = false;
		InputStream in = null;
		OutputStream out = null;

		for (int i = 0; i < localFiles.length; i++) {
			if (localFiles[i].isFile()
					&& localFiles[i].getName().endsWith(".prt")) {
				try {
					LOGGER.debug(localFiles[i].getName());
					in = new BufferedInputStream(new FileInputStream(
							localFiles[i]));
					out = new BufferedOutputStream(new SmbFileOutputStream(
							new SmbFile(serverfolderPath
									+ localFiles[i].getName())));
					byte[] buffer = new byte[1024];
					while (in.read(buffer) != -1) {
						out.write(buffer);
						buffer = new byte[1024];
					}
					localFiles[i].delete();
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					try {
						out.close();
						in.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		b = true;
		LOGGER.debug("uploadPrimaryFileToUGServer>>>>>>>>>>>>>end");
		return b;
	}

	public static boolean downloadPrimaryFile(String currentSysPath,
			String serverPath) throws SmbException, MalformedURLException {
		LOGGER.debug("downloadPrimaryFile>>>>>>>>>>>>>start");

		boolean b = false;

		SmbFile ugtemp = new SmbFile(serverPath);
		SmbFile[] smbFiles = ugtemp.listFiles();

		InputStream in = null;
		OutputStream out = null;

		for (int i = 0; i < smbFiles.length; i++) {
			if (smbFiles[i].isFile()) {
				try {
					LOGGER.debug("smbFileName====>>>>>>>>>"+i+">>>>>>>>>>>>"+smbFiles[i].getName());
					in = new BufferedInputStream(new SmbFileInputStream(
							smbFiles[i]));
					out = new BufferedOutputStream(new FileOutputStream(
							new File(currentSysPath + File.separator
									+ smbFiles[i].getName())));

					byte[] buffer = new byte[1024];
					while (in.read(buffer) != -1) {
						out.write(buffer);
						buffer = new byte[1024];
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					try {
						out.close();
						in.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}

		LOGGER.debug("文件下载成功");
		b = true;
		LOGGER.debug("downloadPrimaryFile>>>>>>>>>>>>>end");
		return b;
	}
	
	

	public static boolean invokeUGServer(Map<String, String> signInfo,
			String host) throws IOException {
		LOGGER.debug("invokeUGServer>>>>>>>>>>>>>start");
		boolean flag = false;

		MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
		HttpClient httpClient = new HttpClient(connectionManager);
		httpClient.getParams().setParameter(
				HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
		HostConfiguration hostConfig = httpClient.getHostConfiguration();
		hostConfig.setHost(host, 8080);
		
		PostMethod postMethod = new PostMethod(
				"/cadSignServer/servlet/cadSign?className=ext.action.UGSignAction");
//		postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT,3000);
//		postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
//				new DefaultHttpMethodRetryHandler());
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(bos);
		oos.writeObject(signInfo);
		RequestEntity requestEntity = new ByteArrayRequestEntity(
				bos.toByteArray(), "multipart/form-data;charset=utf-8");
		postMethod.setRequestEntity(requestEntity);
		httpClient.executeMethod(postMethod);
		int status = postMethod.getStatusLine().getStatusCode();
		if (status == HttpStatus.SC_OK) {
			flag = true;
		}
		oos.close();
		LOGGER.debug("invokeUGServer>>>>>>>>>>>>>end");
		return flag;
	}

}
